package org.eiahe.hr.training.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.github.linpeilie.Converter;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import cn.dev33.satoken.stp.StpUtil;
import org.ehe.common.core.constant.RoleKeyConstants;
import org.ehe.common.satoken.utils.LoginHelper;
import org.eiahe.hr.training.domain.HrTrainingCourseStudent;
import org.eiahe.hr.training.domain.vo.HrTrainingRecordVo;
import org.eiahe.hr.training.domain.HrTrainingRecord;
import org.eiahe.hr.training.domain.bo.HrTrainingRecordBo;
import org.eiahe.hr.training.mapper.HrTrainingCourseStudentMapper;
import org.eiahe.hr.training.mapper.HrTrainingRecordMapper;
import org.eiahe.hr.training.service.IHrTrainingRecordService;
import org.ehe.common.core.exception.ServiceException;
import org.ehe.common.mybatis.core.page.PageQuery;
import org.ehe.common.mybatis.core.page.TableDataInfo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 培训记录Service业务层处理
 *
 * @author zhangnn
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class HrTrainingRecordServiceImpl implements IHrTrainingRecordService {

    private final HrTrainingRecordMapper baseMapper;
    private final Converter converter;
    private final HrTrainingCourseStudentMapper courseStudentMapper;


    /**
     * 查询培训记录
     */
    @Override
    public HrTrainingRecordVo queryById(Long recordId) {
        return baseMapper.selectVoById(recordId);
    }

    /**
     * 查询培训记录列表
     */
    @Override
    public TableDataInfo<HrTrainingRecordVo> queryPageList(HrTrainingRecordBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<HrTrainingRecord> lqw = buildQueryWrapper(bo);

        // 检查用户角色，如果是管理员角色则可以看到所有记录，否则只能看到自己的记录
        if (!(StpUtil.hasRoleOr(RoleKeyConstants.getHrRoles().toArray(new String[0])))) {
            // 获取当前用户ID
            Long userId = LoginHelper.getUserId();
            // 添加用户ID过滤条件
            lqw.eq(HrTrainingRecord::getUserId, userId);
        }

        Page<HrTrainingRecordVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询培训记录列表
     */
    @Override
    public List<HrTrainingRecordVo> queryList(HrTrainingRecordBo bo) {
        LambdaQueryWrapper<HrTrainingRecord> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<HrTrainingRecord> buildQueryWrapper(HrTrainingRecordBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<HrTrainingRecord> lqw = Wrappers.lambdaQuery();
        lqw.eq(ObjectUtil.isNotNull(bo.getEmployeeId()), HrTrainingRecord::getEmployeeId, bo.getEmployeeId());
        lqw.like(StringUtils.isNotBlank(bo.getEmployeeNo()), HrTrainingRecord::getEmployeeNo, bo.getEmployeeNo());
        lqw.like(StringUtils.isNotBlank(bo.getEmployeeName()), HrTrainingRecord::getEmployeeName, bo.getEmployeeName());
        lqw.eq(ObjectUtil.isNotNull(bo.getDeptId()), HrTrainingRecord::getDeptId, bo.getDeptId());
        lqw.eq(ObjectUtil.isNotNull(bo.getCourseId()), HrTrainingRecord::getCourseId, bo.getCourseId());
        lqw.like(StringUtils.isNotBlank(bo.getCourseName()), HrTrainingRecord::getCourseName, bo.getCourseName());
        lqw.eq(StringUtils.isNotBlank(bo.getTrainingType()), HrTrainingRecord::getTrainingType, bo.getTrainingType());
        lqw.eq(StringUtils.isNotBlank(bo.getPassStatus()), HrTrainingRecord::getPassStatus, bo.getPassStatus());
        lqw.eq(StringUtils.isNotBlank(bo.getStatus()), HrTrainingRecord::getStatus, bo.getStatus());
        lqw.orderByDesc(HrTrainingRecord::getCreateTime);
        return lqw;
    }

    /**
     * 新增培训记录
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertByBo(HrTrainingRecordBo bo) {
        HrTrainingRecord add = converter.convert(bo, HrTrainingRecord.class);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setRecordId(add.getRecordId());
        }
        return flag;
    }

    /**
     * 修改培训记录
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateByBo(HrTrainingRecordBo bo) {
        HrTrainingRecord update = converter.convert(bo, HrTrainingRecord.class);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 批量删除培训记录
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteByIds(Collection<Long> recordIds) {
        return baseMapper.deleteByIds(recordIds) > 0;
    }

    /**
     * 批量导入培训记录
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String importTrainingRecord(List<HrTrainingRecordVo> list, Boolean updateSupport) {
        if (ObjectUtil.isEmpty(list)) {
            throw new ServiceException("导入数据不能为空");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();

        for (HrTrainingRecordVo vo : list) {
            try {
                HrTrainingRecord record = converter.convert(vo, HrTrainingRecord.class);
                baseMapper.insert(record);
                successNum++;
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、工号 " + vo.getEmployeeNo() + " 导入失败:" + e.getMessage();
                failureMsg.append(msg);
                log.error(msg, e);
            }
        }

        if (failureNum > 0) {
            failureMsg.insert(0, "导入失败!共 " + failureNum + " 条数据格式不正确,错误如下:");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您,数据已全部导入成功!共 " + successNum + " 条数据");
        }
        return successMsg.toString();
    }

    /**
     * 导出培训记录
     */
    @Override
    public List<HrTrainingRecordVo> exportTrainingRecord(HrTrainingRecordBo bo) {
        LambdaQueryWrapper<HrTrainingRecord> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    /**
     * 完成学习
     *
     * @param courseId
     * @return
     */
    @Override
    public Boolean completeCourseDetail(Long courseId) {
        Long userId = LoginHelper.getUserId();
        HrTrainingRecord hrTrainingRecord = this.baseMapper
                .selectOne(new LambdaQueryWrapper<HrTrainingRecord>()
                    .eq(HrTrainingRecord::getCourseId, courseId));
        if (Objects.nonNull(hrTrainingRecord)) {
            hrTrainingRecord.setStatus("1");
        }
        //更新student表信息
        HrTrainingCourseStudent student = courseStudentMapper.selectOne(new LambdaQueryWrapper<HrTrainingCourseStudent>()
            .eq(HrTrainingCourseStudent::getCourseId,courseId)
            .eq(HrTrainingCourseStudent::getUserId,userId)
        );
        student.setCompleteTime(new Date());
        student.setStudyProgress(100);
        student.setIsCompleted("1");
        student.setIsPassed("1");
        courseStudentMapper.updateById(student);

        hrTrainingRecord.setUpdateBy(LoginHelper.getUserId());
        hrTrainingRecord.setUpdateTime(new Date());
        return this.baseMapper.updateById(hrTrainingRecord) > 0;
    }

    /**
     * 判断当前用户是否已经完成学习
     * @param courseId
     * @param userId
     * @return
     */
    @Override
    public Boolean completeCourseByCourseIdAndEmpId(Long courseId, Long userId) {
        HrTrainingRecord hrTrainingRecord = this.baseMapper.selectOne(new LambdaQueryWrapper<HrTrainingRecord>()
            .eq(HrTrainingRecord::getCourseId, courseId)
            .eq(HrTrainingRecord::getUserId, userId)
            .eq(HrTrainingRecord::getStatus, "1")
        );
        if(Objects.nonNull(hrTrainingRecord)){
            return true;
        }
        return false;
    }
}
